package com.jzy.secondhandbooktradingmanagement.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jzy.secondhandbooktradingmanagement.commom.Result;
import com.jzy.secondhandbooktradingmanagement.entity.TradeOrder;
import com.jzy.secondhandbooktradingmanagement.service.ITradeOrderService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/order")
public class TradeOrderController {

    @Resource
    ITradeOrderService tradeOrderService;

    @PostMapping
    public Result<?> save(@RequestBody TradeOrder tradeOrder) {
        try {
            TradeOrder createdOrder = tradeOrderService.createOrder(tradeOrder);
            return Result.success(createdOrder);
        } catch (Exception e) {
            return Result.error("-1", e.getMessage());
        }
    }

    @PutMapping
    public Result<?> update(@RequestBody TradeOrder tradeOrder) {
        tradeOrderService.updateById(tradeOrder);
        return Result.success();
    }

    @PostMapping("/deleteBatch")
    public Result<?> deleteBatch(@RequestBody List<Integer> ids) {
        tradeOrderService.removeBatchByIds(ids);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        tradeOrderService.deleteOrder(id);
        return Result.success();
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                              @RequestParam(name = "search1", defaultValue = "") String search1, // Order No
                              @RequestParam(name = "search2", defaultValue = "") String search2, // User ID
                              @RequestParam(name = "search3", defaultValue = "") String search3) { // Status
        Page<TradeOrder> page = tradeOrderService.findPage(pageNum, pageSize, search1, search2, search3);
        return Result.success(page);
    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Integer id) {
        TradeOrder tradeOrder = tradeOrderService.getOrderById(id);
        if (tradeOrder == null) {
            return Result.error("-1", "订单不存在");
        }
        return Result.success(tradeOrder);
    }
}
